package com.xxx.store.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxx.store.entity.Post;
import com.xxx.store.entity.PostImg;
import com.xxx.store.mapper.UserMapper;
import com.xxx.store.service.PostImgService;
import com.xxx.store.service.PostService;
import com.xxx.store.service.UserService;
import com.xxx.store.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-04-26
 */
@RestController
@RequestMapping("/post")
public class PostController extends BaseController<Post, PostService>{

    @Autowired
    PostService postService;
    @Autowired
    PostImgService postImgService;
    @Autowired
    UserMapper userMapper;

    @Override
    public Result add(@RequestBody Post post) {
        postService.save(post);
        for (String url : post.getImgList()) {
            PostImg postImg = new PostImg();
            postImg.setPostId(post.getId());
            postImg.setUrl(url);
            postImgService.save(postImg);
        }
        return Result.ok("添加成功", post);
    }

    @Override
    public Result list() {
        QueryWrapper<Post> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        List<Post> list = postService.list(qw);
        for (Post post : list) {
            QueryWrapper<PostImg> imgQueryWrapper = new QueryWrapper<>();
            imgQueryWrapper.eq("post_id", post.getId());
            post.setPostImgList(postImgService.list(imgQueryWrapper));
            post.setUser(userMapper.getByIdIgnore(post.getUserId()));
        }
        return Result.ok(list);
    }
}

